<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace builder\helper;

use Yii;
use yii\helpers\Json;

/**
 * HTTP
 * @author cleverstone
 * @since ym2.0
 */
class Http
{
    /**
     * 客户端是否允许接收json
     * @return bool
     */
    public static function isAcceptJson()
    {
        $acceptableTypes = Yii::$app->getRequest()->getAcceptableContentTypes();
        if (!empty($acceptableTypes) && in_array('application/json', array_keys($acceptableTypes))) {
            return true;
        }

        return false;
    }

    /**
     * 发起请求
     * @param string $url 请求链接
     * @param string $method 请求动作
     * @param string $contentType 内容类型
     * @param array $data 传输数据
     * @param int $timeOut 设置cURL允许执行的最长秒数
     * @return array
     */
    public static function req($url, $method = 'get', $contentType = '', array $data = [], $timeOut = 20)
    {
        $method = strtolower($method);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);

        switch ($method) {
            case 'post':
                switch ($contentType) {
                    case 'multipart':
                        $head = 'Content-Type: multipart/form-data; charset=UTF-8';
                        $param = $data;
                        break;
                    case 'xml':
                        $head = 'Content-Type: text/xml; charset=UTF-8';
                        $param = Arr::toXml($data);
                        break;
                    case 'json':
                        $head = 'Content-Type: application/json; charset=UTF-8';
                        $param = Json::encode($data);
                        break;
                    case 'urlencoded':
                    default:
                        $head = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8';
                        $param = http_build_query($data);
                }

                curl_setopt($ch, CURLOPT_HTTPHEADER, [$head]);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                break;
            case 'get':
            default:
                ;
        }

        curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);

            return ['code' => 500, 'result' => $error];
        }

        curl_close($ch);
        return ['code' => 200, 'result' => $result];
    }
}